package com.pp.web.aop;


import com.pp.common.anno.ArgsValidate;
import com.pp.common.bean.ResultBuilder;
import com.pp.common.constant.enums.CoreMsg;
import com.pp.common.utils.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Map;

/**
 *  参数校验
 */
@Aspect
@Component
@Slf4j
public class ArgsValidateAspect implements Ordered{


    /**
     * 此方法只针对入参格式是JSON格式化的请求
     * @param o
     * @return
     */
    @Around("@annotation(argsValidate)")
    public Object processor(ProceedingJoinPoint o, ArgsValidate argsValidate) throws Throwable {
        Map reqArgs = (Map)o.getArgs()[0];
        Field declaredField = argsValidate.validateClass().getDeclaredField(argsValidate.value());
        declaredField.setAccessible(true);
        String [] validateArgs = (String [])declaredField.get(argsValidate.validateClass().newInstance());
        if(!ValidateUtils.checkParams(reqArgs, validateArgs)){
            return ResultBuilder.error(CoreMsg.REQUEST_PARAMETER_ERROR);
        }
        return o.proceed();
    }

    public int getOrder() {
        return 1;
    }
}
